package com.yjz.study.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.yjz.common.base.BaseActivity
import com.yjz.common.extend.showToast
import com.yjz.study.R
import com.yjz.study.account.AccountManager
import com.yjz.study.adapter.detail.GoodsDetailAttrItem
import com.yjz.study.adapter.detail.GoodsDetailCommentItem
import com.yjz.study.adapter.detail.GoodsDetailGalleryItem
import com.yjz.study.adapter.detail.GoodsDetailHeadItem
import com.yjz.study.adapter.detail.GoodsDetailShopInfoItem
import com.yjz.study.adapter.detail.GoodsDetailSimilarTitleItem
import com.yjz.study.adapter.home.GoodsItem
import com.yjz.study.arouter.ARouterLogic
import com.yjz.study.http.entity.res.GoodsDetailModel
import com.yjz.study.http.entity.res.GoodsModel
import com.yjz.study.http.entity.res.selectPrice
import com.yjz.study.listener.GoodsDetailTitleScrollerListener
import com.yjz.study.viewmodel.GoodsDetailViewModel
import com.yjz.ui.recycler.item.HiAdapter
import com.yjz.ui.recycler.item.HiDataItem
import com.yjz.ui.view.EmptyView
import com.yjz.ui.view.HiStatusBar
import com.yjz.ui.view.IconFontTextView

/**
 *作用 : 商品详情页
 *作者 : yjz
 *时间 : 2025/3/29 15:17
 */
@Route(path = ARouterLogic.Path.GOOD_DETAIL)
class GoodDetailActivity : BaseActivity() {

    @JvmField
    @Autowired
    var goodsId: String = ""

    @JvmField
    @Autowired
    var goodsModel: GoodsModel? = null

    private lateinit var viewModel: GoodsDetailViewModel

    private var emptyView: EmptyView? = null

    private lateinit var rootContainer: ConstraintLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var actionOrder: TextView
    private lateinit var actionFavorite: IconFontTextView

    override fun getLayoutId() = R.layout.activity_good_detail

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        HiStatusBar.setStatusBar(this, true, Color.TRANSPARENT, true)
        ARouterLogic.inject(this)
        assert(!TextUtils.isEmpty(goodsId)) {
            "goodsId must bot be null"
        }
        // 初始化布局
        initView()
        // 根据传递进来的数据预显示数据
        preBindData()
        // 请求详情数据
        queryDetailData()
    }

    private fun preBindData() {
        if (goodsModel == null) return
        val hiAdapter = recyclerView.adapter as HiAdapter
        // notify 为false是因为adapter可能还没有初始化好
        hiAdapter.addItemAt(
            0, GoodsDetailHeadItem(
                goodsModel!!.sliderImages,
                selectPrice(goodsModel!!.groupPrice, goodsModel!!.marketPrice),
                goodsModel!!.completedNumText,
                goodsModel!!.goodsName
            ), false
        )
    }

    private fun initView() {
        val navBar = findViewById<FrameLayout>(R.id.nav_bar)
        rootContainer = findViewById(R.id.root_container)
        findViewById<IconFontTextView>(R.id.action_back).setOnClickListener {
            finish()
        }
        recyclerView = findViewById(R.id.recycler_view)
        recyclerView.layoutManager = GridLayoutManager(this, 2)
        recyclerView.adapter = HiAdapter(this)
        recyclerView.addOnScrollListener(GoodsDetailTitleScrollerListener(100f) {
            navBar.setBackgroundColor(it)
        })
    }

    private fun queryDetailData() {
        viewModel = GoodsDetailViewModel.get(goodsId, this)
        viewModel.queryDetailData().observe(this) {
            if (it == null) {
                showEmptyView()
            } else {
                bindData(it)
            }
        }
    }

    private fun showEmptyView() {
        if (emptyView == null) {
            emptyView = EmptyView(this)
            emptyView!!.setIcon(R.string.if_empty3)
            emptyView!!.setDesc(getString(com.yjz.ui.R.string.list_empty))
            emptyView!!.layoutParams = ConstraintLayout.LayoutParams(-1, -1)
            emptyView!!.setBackgroundColor(Color.WHITE)
            emptyView!!.setButton(getString(com.yjz.ui.R.string.list_empty_action), View.OnClickListener {
                viewModel.queryDetailData()
            })
            rootContainer.addView(emptyView)
        }
        rootContainer.visibility = View.GONE
        emptyView!!.visibility = View.VISIBLE
    }

    private fun bindData(detailModel: GoodsDetailModel) {

        recyclerView.visibility = View.VISIBLE
        emptyView?.visibility = View.GONE

        val adapter = recyclerView.adapter as HiAdapter
        val itemList = mutableListOf<HiDataItem<*, *>>()
        // 头部模块
        itemList.add(
            GoodsDetailHeadItem(
                detailModel.sliderImages,
                selectPrice(detailModel.groupPrice, detailModel.marketPrice),
                detailModel.completedNumText,
                detailModel.goodsName
            )
        )
        // 评论模块
        itemList.add(GoodsDetailCommentItem(detailModel))
        // 店铺介绍
        itemList.add(GoodsDetailShopInfoItem(detailModel))
        // 商品描述
        itemList.add(GoodsDetailAttrItem(detailModel))
        // 商品相册
        detailModel.sliderImages?.let {
            detailModel.sliderImages.forEach {
                itemList.add(GoodsDetailGalleryItem(it))
            }
        }
        // 相识商品
        detailModel.similarGoods?.let {
            itemList.add(GoodsDetailSimilarTitleItem())
            detailModel.similarGoods.forEach {
                itemList.add(GoodsItem(it, false))
            }
        }
        adapter.clearItems()
        adapter.addItems(itemList, true)

        actionOrder = findViewById<TextView>(R.id.action_order)
        actionFavorite = findViewById<IconFontTextView>(R.id.action_favorite)

        updateFavoriteActionFace(detailModel.isFavorite)
        updateOrderActionFace(detailModel)
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderActionFace(detailModel: GoodsDetailModel) {
        actionOrder.text = "${
            selectPrice(
                detailModel.groupPrice,
                detailModel.marketPrice
            )
        }" + getString(R.string.detail_order_action)
    }

    private fun updateFavoriteActionFace(favorite: Boolean) {
        actionFavorite.setOnClickListener {
            toggleFavorite()
        }
        actionFavorite.setTextColor(
            ContextCompat.getColor(
                this,
                if (favorite) com.yjz.ui.R.color.color_dd2 else com.yjz.ui.R.color.color_999
            )
        )
    }

    /**
     * 同步收藏操作
     */
    private fun toggleFavorite() {
        if (!AccountManager.isLogin()) { // 如果没登录先执行登录操作
            AccountManager.login(this) { loginSuccess ->
                if (loginSuccess) { // 登录成功手动触发收藏
                    toggleFavorite()
                }
            }
        } else {
            // 防止多次点击
            actionFavorite.isClickable = false
            viewModel.toggleFavorite().observe(this) { success ->
                if (success != null) {
                    //网络成功
                    updateFavoriteActionFace(success)
                    val message = if (success) getString(R.string.detail_favorite_success) else getString(R.string.detail_cancel_favorite)
                    showToast(message)
                } else {
                    //网络失败
                }
                actionFavorite.isClickable = true
            }
        }
    }
}